# -*- coding: utf-8 -*-
from celery import task
from celery.task.base import periodic_task
from celery.schedules import crontab
from blueking.component.shortcuts import get_client_by_user
from uxsino.models import Host,Biz, BkCloud
import datetime
from __builtin__ import str

def get_hosts():
#     logger.error("***************************************");
    client = get_client_by_user("admin");
    params = {
        "page": {"start": 0, "limit": 5, "sort": "bk_host_id"},
        "ip": {
            "flag": "bk_host_innerip|bk_host_outerip",
            "exact": 1,
            "data": []
        },
        "condition": [
            {
                "bk_obj_id": "host",
                "fields": [],
                "condition": []
            },
            {"bk_obj_id": "module", "fields": [], "condition": []},
            {"bk_obj_id": "set", "fields": [], "condition": []},
            {
                "bk_obj_id": "biz",
                "fields": [
                    "default",
                    "bk_biz_id",
                    "bk_biz_name",
                ],
                "condition": [
                    {
                        "field": "bk_biz_id",
                        "operator": "$eq",
                        "value": 2
                    }
                ]
            }
        ]
    };
    result = client.cc.search_host(params);
    
    if result.get("code") == 0:
        return result.get("data").get("info");
    else:
        return [];

def saveHostdb(datas):
    if datas:
        for itm in datas:
            host = itm.get("host");
            st = itm.get("set");
            bizes = dict([(str(bz.get("bk_biz_id")), bz) for bz in itm.get("biz")]); # 去重
            hes = Host.objects.filter(ip=host.get("bk_host_innerip"));
            bzCloudItms = host.get("bk_cloud_id");
            h = Host();
            if len(hes) > 0 :
                h = hes[0];
            h.disk = host.get("bk_disk");
            h.mem = host.get("bk_mem");
            h.ip = host.get("bk_host_innerip");
            h.model = host.get("bk_cpu_module");
            h.os_type = host.get("bk_os_name");
            if len(st) > 0:
                h.area = st[0].get("bk_set_name");
                h.carea = st[0].get("TopSetName");
            h.save();
            bizDbDatas = Biz.objects.filter(host=h);
            ## 处理云区域
            dbCloundData = BkCloud.objects.filter(host = h);
            if dbCloundData:
                for c in dbCloundData:
                    c.delete();
            if bzCloudItms:
                for nc in bzCloudItms:
                    ncdb = BkCloud(host=h, bk_obj_name=nc.get("bk_obj_name"), bk_obj_id= nc.get("bk_obj_id"), bk_obj_icon = nc.get("bk_obj_icon"), bk_inst_id = nc.get("bk_inst_id"), bk_inst_name = nc.get("bk_inst_name"))
                    ncdb.save()
            """ """
            bizIds = bizes.keys();
            for dbBiz in bizDbDatas:
                if bizIds.count(str(dbBiz.bz_id)) == 0: # 删除
                    dbBiz.delete();
                else: #执行更新
                    biz = bizes.get(str(dbBiz.bz_id));
                    if biz:
#                         logger.error("***************************")
#                         logger.error(dbBiz);
#                         logger.error(biz);
#                         logger.error("***************************")
                        dbBiz.bz_name = biz.get("bk_biz_name");
                        dbBiz.save();
            """ """
            #将未保存的数据保存
            bizIds = [str(db.bz_id) for db in bizDbDatas];
            for nbz in bizes.values():
                if bizIds.count(str(nbz.get("bk_biz_id"))) ==0:
                    newBiz = Biz(host=h, bz_id=str(nbz.get("bk_biz_id")), bz_name = nbz.get("bk_biz_name"));
                    newBiz.save();
    return;

@task()
def sync_host():
#     logger.info("执行了同步主机的请求");
    hosts = get_hosts();
    if hosts:
        saveHostdb(hosts);
    return;

def join_job():
    now = datetime.datetime.now();
#     logger.info("同步主机数据任务启动，将在60s后执行，当前时间：{}".format(now))
    sync_host.apply_async(args=[], eta=now + datetime.timedelta(seconds=60));
    return;

@periodic_task(run_every=crontab(minute='*/1', hour='*', day_of_week="*"))
def do_sync():
    """周期性同步主机数据"""
    join_job();
    return;